<template>
  <div>
    <el-dialog
      :title="type === 'add' ? '新增用户' : '编辑用户'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 表单 -->
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        size="small"
        style="margin-right: 30px"
        :rules="rules"
      >
        <el-form-item prop="name" label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="form.age"></el-input>
        </el-form-item>
        <el-form-item label="学院">
          <el-input v-model="form.study"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-input v-model="form.class"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Dialog',
  props: {
    type: {
      type: String
    },
    row: {
      type: Object
    }
  },
  data () {
    return {
      dialogVisible: true,
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      form: {
        name: '', //姓名
        age: '', //年龄
        study: '', //学院
        class: '', //班级
        phone: '', //联系方式
      }
    }
  },
  methods: {
    // 关闭对话框
    handleClose () {
      this.$emit('close')
    },
    // 确认
    submit () {
      this.$refs.form.validate(value => {
        if (value) {
          this.$emit('submit', this.form, this.type)
          this.handleClose()
          const msg = this.type === 'add' ? '新增用户成功！' : '编辑用户成功'
          this.$message.success(msg)
        }
      })
    }
  },
  created () {
    if (this.type === 'add') {
      // 新增
    } else if (this.type === 'edit') {
      // 修改
      this.form = JSON.parse(JSON.stringify(this.row)) // 深拷贝，实现一个独立的副本，避免污染表格中的数据
    }
  },
}
</script>

<style scoped>
</style>